﻿using BestWise.Common;
using System;
using System.Data.SqlTypes;

namespace Newtonsoft.Json.Converters
{
    /// <summary>
    /// 将日期时间型序列化成时间戳。
    /// </summary>
    internal class JsonDateTimeConverter : DateTimeConverterBase
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            if (reader.TokenType == JsonToken.Date)
                return (DateTime)reader.Value;
            if(reader.TokenType==JsonToken.Integer)
            {
                long ticks = reader.Value != null ? (long)reader.Value : 0;
                return ticks.ToDateTime();
            }
            if (reader.TokenType == JsonToken.String)
            {
                string str = reader.Value.ToString();
                if (str.IsNumeric())
                    return Convert.ToInt64(str).ToDateTime();
                else
                {
                    DateTime date = SqlDateTime.MinValue.Value;
                    if (DateTime.TryParse(str, out date))
                        return date;
                }
            }
            return SqlDateTime.MinValue.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            long ticks;
            if (value is DateTime)
            {
                TimeSpan ts = new TimeSpan(Convert.ToDateTime(value).ToUniversalTime().Ticks - new DateTime(1970, 1, 1).Ticks);
                ticks = (long)ts.TotalMilliseconds;
            }
            else
            {
                throw new Exception("时间格式错误.2");
            }
            writer.WriteValue(ticks);
        }
    }
}